package cn.net.isir.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @author liuxubo
 * @filename DateUtils.java
 * @package cn.net.isir.common
 * @email lxb@isir.net.cn
 * @date 2018/10/05
 * @comment
 * @since 1.7
 */
public class DateUtils {
    // 声明log4j日志
    private static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(DateUtils.class);
    /**
     * 一整天的毫秒数
     */
    public static long dayTimeInMillis = 1000 * 60 * 60 * 24;
    public static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 获取今天0点的毫秒数
     *
     * @return 今天0点的毫秒数
     */
    public static long getTodayZeroTimeInMillis() {
        Calendar todayCalendar = Calendar.getInstance();
        todayCalendar.set(Calendar.HOUR_OF_DAY, 0);//.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        todayCalendar.set(Calendar.MINUTE, 0);
        todayCalendar.set(Calendar.SECOND, 0);
        todayCalendar.set(Calendar.MILLISECOND, 0);
        return todayCalendar.getTimeInMillis();
    }

    /**
     * 获取今天已经过的毫秒数
     *
     * @return 今天已经过的毫秒数
     */
    public static long getTodayTimeInMillis() {
        Calendar todayCalendar = Calendar.getInstance();
        todayCalendar.set(Calendar.HOUR_OF_DAY, 0);//.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        todayCalendar.set(Calendar.MINUTE, 0);
        todayCalendar.set(Calendar.SECOND, 0);
        todayCalendar.set(Calendar.MILLISECOND, 0);
        return Calendar.getInstance().getTimeInMillis() - todayCalendar.getTimeInMillis();
    }

    /**
     * 获取本周已经经过的毫秒数
     *
     * @param firstDayOfWeek 一周的第一天，周日是1，周一是2，周二是3......周六是7
     *                       可以直接使用Calendar.MONDAY (表示周一是第一天)，Calendar.TUESDAY (表示周二是第一天)...等进行设置
     * @return 本周已经经过的毫秒数
     */
    public static long getThisWeekTimeInMillis(int firstDayOfWeek) {

        Calendar calendar = Calendar.getInstance();
        //今天是本周第几天，本周从周日开始，周日value是1
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        int days = dayOfWeek - firstDayOfWeek;
        if (firstDayOfWeek > dayOfWeek) {
            days = dayOfWeek + 7 - firstDayOfWeek;
        }
        return dayTimeInMillis * days + getTodayTimeInMillis();
    }

    /**
     * 判断某个日期是否在几天之内
     *
     * @param date    要判断的日期
     * @param days    天数，0表示今天全天之内(忽略fullDay参数)，-1表示昨天，-2表示前天，1表示明天，2表示后天
     * @param fullDay true表示计算到今天结束(忽略今天的时分秒)，false表示精确判断到今天的时分秒
     * @return true表示包含，false表示不包含
     */
    public static boolean isInDays(Date date, int days, boolean fullDay) {
        Date now = new Date();
        long nowTime = now.getTime();
        long dateTime = date.getTime();

        //时间相等则一定包含
        if (nowTime == dateTime) {
            return true;
        }

        //之前的时间，不能晚于当前时间
        if (days < 0) {
            if (dateTime > nowTime) {
                return false;
            }
        }
        //之后的时间，不能早于当前时间
        if (days > 0) {
            if (dateTime < nowTime) {
                return false;
            }
        }

        //天数换算成毫秒数
        long daysTime = days * dayTimeInMillis;
        //用于判断之前时间
        long beforeTime = nowTime;
        //用于判断之后时间
        long afterTime = nowTime;
        //全天计算后的两个时间
        if (fullDay) {
            beforeTime = getTodayZeroTimeInMillis();
            afterTime = getTodayZeroTimeInMillis() + dayTimeInMillis;
        }
        //如果是今天
        if (days == 0) {
            return dateTime > getTodayZeroTimeInMillis() && dateTime < getTodayZeroTimeInMillis() + dayTimeInMillis;
        }
        if (days < 0) {
            //如果【“当前时间点”】【提前几天后】早于【判断时间】，则在几天之内
            return new Date(beforeTime + daysTime).before(date);
        }
        if (days > 0) {
            //如果【“当前时间点”】【延后几天后】晚于【判断时间】，则在几天内
            return new Date(afterTime + daysTime).after(date);
        }
        return false;
    }

    public static boolean isInDateRegion(long date, long startTime, long endTime) {
        return date > startTime && date < endTime;
    }

    /**
     * 格式化时间
     *
     * @param date   需要格式化输出日期
     * @param format 格式（参考：yyyy-MM-dd HH:mm:ss）
     * @return 格式化后的字符串
     */
    public static String format(Date date, String format) {
        if (date == null) {
            date = new Date();
        }
        return new SimpleDateFormat(format).format(date);
    }

    /**
     * 获取现在当前时间的字符串
     *
     * @return 现在当前时间的字符串
     */
    public static String getNowStr() {
        return simpleDateFormat.format(new Date());
    }

    /**
     * 格式化时间
     *
     * @param dateStr 日期字符串
     * @param format  格式（参考：yyyy-MM-dd HH:mm:ss）
     * @return 输出Date对象
     */
    public static Date parse(String dateStr, String format) {
        if (dateStr == null) {
            return null;
        }
        try {
            return new SimpleDateFormat(format).parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据字符串生成时间对象
     *
     * @param dateStr 时间字符串"yyyy-MM-dd HH:mm:ss"
     * @return Date对象
     */
    public static Date getDateByString(String dateStr) {

        try {
            return simpleDateFormat.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 获取 当前年、半年、季度、月、日、小时 开始结束时间
     */

    private final static SimpleDateFormat shortSdf = new SimpleDateFormat("yyyy-MM-dd");
    private final static SimpleDateFormat longHourSdf = new SimpleDateFormat("yyyy-MM-dd HH");
    ;
    private final static SimpleDateFormat longSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    ;


    /**
     * 获得本周的第一天，周一
     *
     * @return
     */
    public static Date getCurrentWeekDayStartTime() {
        Calendar c = Calendar.getInstance();
        try {
            int weekday = c.get(Calendar.DAY_OF_WEEK) - 2;
            c.add(Calendar.DATE, -weekday);
            c.setTime(longSdf.parse(shortSdf.format(c.getTime()) + " 00:00:00"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return c.getTime();
    }

    /**
     * 获得本周的最后一天，周日
     *
     * @return
     */
    public static Date getCurrentWeekDayEndTime() {
        Calendar c = Calendar.getInstance();
        try {
            int weekday = c.get(Calendar.DAY_OF_WEEK);
            c.add(Calendar.DATE, 8 - weekday);
            c.setTime(longSdf.parse(shortSdf.format(c.getTime()) + " 23:59:59"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return c.getTime();
    }

    /**
     * 获得本天的开始时间
     *
     * @return
     */
    public static Date getCurrentDayStartTime() {
        Date now = new Date();
        try {
            now = shortSdf.parse(shortSdf.format(now));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return now;
    }

    /**
     * 获得本天的结束时间
     *
     * @return
     */
    public static Date getCurrentDayEndTime() {
        Date now = new Date();
        try {
            now = longSdf.parse(shortSdf.format(now) + " 23:59:59");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return now;
    }

    /**
     * 获得本小时的开始时间
     *
     * @return
     */
    public static Date getCurrentHourStartTime() {
        Date now = new Date();
        try {
            now = longHourSdf.parse(longHourSdf.format(now));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return now;
    }

    /**
     * 获得本小时的结束时间
     *
     * @return
     */
    public static Date getCurrentHourEndTime() {
        Date now = new Date();
        try {
            now = longSdf.parse(longHourSdf.format(now) + ":59:59");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return now;
    }

    /**
     * 获得本月的开始时间
     *
     * @return
     */
    public static Date getCurrentMonthStartTime() {
        Calendar c = Calendar.getInstance();
        Date now = null;
        try {
            c.set(Calendar.DATE, 1);
            now = shortSdf.parse(shortSdf.format(c.getTime()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return now;
    }

    /**
     * 本月的结束时间
     *
     * @return
     */
    public static Date getCurrentMonthEndTime() {
        Calendar c = Calendar.getInstance();
        Date now = null;
        try {
            c.set(Calendar.DATE, 1);
            c.add(Calendar.MONTH, 1);
            c.add(Calendar.DATE, -1);
            now = longSdf.parse(shortSdf.format(c.getTime()) + " 23:59:59");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return now;
    }

    /**
     * 当前年的开始时间
     *
     * @return
     */
    public static Date getCurrentYearStartTime() {
        Calendar c = Calendar.getInstance();
        Date now = null;
        try {
            c.set(Calendar.MONTH, 0);
            c.set(Calendar.DATE, 1);
            now = shortSdf.parse(shortSdf.format(c.getTime()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return now;
    }

    /**
     * 当前年的结束时间
     *
     * @return
     */
    public static Date getCurrentYearEndTime() {
        Calendar c = Calendar.getInstance();
        Date now = null;
        try {
            c.set(Calendar.MONTH, 11);
            c.set(Calendar.DATE, 31);
            now = longSdf.parse(shortSdf.format(c.getTime()) + " 23:59:59");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return now;
    }

    /**
     * 当前季度的开始时间
     *
     * @return
     */
    public static Date getCurrentQuarterStartTime() {
        Calendar c = Calendar.getInstance();
        int currentMonth = c.get(Calendar.MONTH) + 1;
        Date now = null;
        try {
            if (currentMonth >= 1 && currentMonth <= 3)
                c.set(Calendar.MONTH, 0);
            else if (currentMonth >= 4 && currentMonth <= 6)
                c.set(Calendar.MONTH, 3);
            else if (currentMonth >= 7 && currentMonth <= 9)
                c.set(Calendar.MONTH, 4);
            else if (currentMonth >= 10 && currentMonth <= 12)
                c.set(Calendar.MONTH, 9);
            c.set(Calendar.DATE, 1);
            now = longSdf.parse(shortSdf.format(c.getTime()) + " 00:00:00");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return now;
    }

    /**
     * 当前季度的结束时间
     *
     * @return
     */
    public static Date getCurrentQuarterEndTime() {
        Calendar c = Calendar.getInstance();
        int currentMonth = c.get(Calendar.MONTH) + 1;
        Date now = null;
        try {
            if (currentMonth >= 1 && currentMonth <= 3) {
                c.set(Calendar.MONTH, 2);
                c.set(Calendar.DATE, 31);
            } else if (currentMonth >= 4 && currentMonth <= 6) {
                c.set(Calendar.MONTH, 5);
                c.set(Calendar.DATE, 30);
            } else if (currentMonth >= 7 && currentMonth <= 9) {
                c.set(Calendar.MONTH, 8);
                c.set(Calendar.DATE, 30);
            } else if (currentMonth >= 10 && currentMonth <= 12) {
                c.set(Calendar.MONTH, 11);
                c.set(Calendar.DATE, 31);
            }
            now = longSdf.parse(shortSdf.format(c.getTime()) + " 23:59:59");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return now;
    }

    /**
     * 获取前/后半年的开始时间
     *
     * @return
     */
    public static Date getHalfYearStartTime() {
        Calendar c = Calendar.getInstance();
        int currentMonth = c.get(Calendar.MONTH) + 1;
        Date now = null;
        try {
            if (currentMonth >= 1 && currentMonth <= 6) {
                c.set(Calendar.MONTH, 0);
            } else if (currentMonth >= 7 && currentMonth <= 12) {
                c.set(Calendar.MONTH, 6);
            }
            c.set(Calendar.DATE, 1);
            now = longSdf.parse(shortSdf.format(c.getTime()) + " 00:00:00");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return now;

    }

    /**
     * 获取前/后半年的结束时间
     *
     * @return
     */
    public static Date getHalfYearEndTime() {
        Calendar c = Calendar.getInstance();
        int currentMonth = c.get(Calendar.MONTH) + 1;
        Date now = null;
        try {
            if (currentMonth >= 1 && currentMonth <= 6) {
                c.set(Calendar.MONTH, 5);
                c.set(Calendar.DATE, 30);
            } else if (currentMonth >= 7 && currentMonth <= 12) {
                c.set(Calendar.MONTH, 11);
                c.set(Calendar.DATE, 31);
            }
            now = longSdf.parse(shortSdf.format(c.getTime()) + " 23:59:59");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return now;
    }

    public static void main(String[] args) {
        logger.info(getThisWeekTimeInMillis(Calendar.SATURDAY));
        logger.info(getThisWeekTimeInMillis(Calendar.MONDAY));
    }
}
